//
//  BGTabBar.swift
//  WeiboSwift
//
//  Created by 战场原黑仪 on 16/7/19.
//  Copyright © 2016年 战场原黑仪. All rights reserved.
//

import UIKit

protocol BGTabBarDelegate: NSObjectProtocol {
    func composeButtonClick()
}

class BGTabBar: UITabBar {

    //监听点击事件
//    var closure:(()->())?
    // 声明代理
    weak var bgDelegate: BGTabBarDelegate?
    
    
    //中间按钮点击
    @objc private func addWeiBo() {
        bgDelegate?.composeButtonClick()
    }
    
    //MARK: - 添加控件
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(composeButton)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 设置按钮frame
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let width: CGFloat = self.frame.width * 0.2
        var index: CGFloat = 0
        
        for item in subviews {
            
            if item.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                item.frame.origin.x = index * width
                item.frame.size.width = width
                index++
                
                //给按钮让位
                if index==2 {
                    index++
                }
            }
        }
        
        composeButton.center.x = self.frame.width * 0.5
        composeButton.center.y = self.frame.height * 0.5
        
    }
    
    //MARK: - 懒加载
    lazy var composeButton: UIButton = {
        let btn = UIButton()
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        btn.addTarget(self, action: #selector(addWeiBo), forControlEvents: .TouchUpInside)
        
        btn.sizeToFit()
        
        return btn;
    }()

}
